/***************************************************
  This is our library for the Adafruit ILI9341 Breakout and Shield
  ----> http://www.adafruit.com/products/1651

  Check out the links above for our tutorials and wiring diagrams
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional)
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#include "ili9341.h"
#include "delay.h"
#include "_config_lib_graphics.h"

static u16 _width = gfxWIDTH;
static u16 _height = gfxHEIGHT;

//------------------------------------------------------------------------------------------------------------------
// Descrição:	Inicializa pinos do controlador e o driver controlador
//				O acesso é feito via barramento SPI no modo padrão com velocidade máxima de 8MHz
// Parametros	Nenhum
// Retorna: 	Nada
//------------------------------------------------------------------------------------------------------------------
void tft_Init(void) {
	ili9341_SetupPorts();	// Configurar os pinos de controle

	#if (ILI9341_USE_RESET == pdON)
	tft_Reset();
	#endif

  	tft_WriteCommand(0xEF);
  	tft_WriteData(0x03);
  	tft_WriteData(0x80);
  	tft_WriteData(0x02);

 	tft_WriteCommand(0xCF);
  	tft_WriteData(0x00);
  	tft_WriteData(0XC1);
  	tft_WriteData(0X30);

  	tft_WriteCommand(0xED);
  	tft_WriteData(0x64);
  	tft_WriteData(0x03);
  	tft_WriteData(0X12);
  	tft_WriteData(0X81);

  	tft_WriteCommand(0xE8);
  	tft_WriteData(0x85);
  	tft_WriteData(0x00);
  	tft_WriteData(0x78);

  	tft_WriteCommand(0xCB);
  	tft_WriteData(0x39);
  	tft_WriteData(0x2C);
  	tft_WriteData(0x00);
  	tft_WriteData(0x34);
  	tft_WriteData(0x02);

  	tft_WriteCommand(0xF7);
  	tft_WriteData(0x20);

  	tft_WriteCommand(0xEA);
  	tft_WriteData(0x00);
  	tft_WriteData(0x00);

  	tft_WriteCommand(ILI9341_PWCTR1);    //Power control
  	tft_WriteData(0x23);   //VRH[5:0]

  	tft_WriteCommand(ILI9341_PWCTR2);    //Power control
  	tft_WriteData(0x10);   //SAP[2:0];BT[3:0]

  	tft_WriteCommand(ILI9341_VMCTR1);    //VCM control
  	tft_WriteData(0x3e); //Â¶Ã”Â±ÃˆÂ¶ÃˆÂµÃ·Â½Ãš
  	tft_WriteData(0x28);

  	tft_WriteCommand(ILI9341_VMCTR2);    //VCM control2
  	tft_WriteData(0x86);  //--

  	tft_WriteCommand(ILI9341_MADCTL);    // Memory Access Control
  	tft_WriteData(0x48);

  	tft_WriteCommand(ILI9341_PIXFMT);
  	tft_WriteData(0x55);

  	tft_WriteCommand(ILI9341_FRMCTR1);
  	tft_WriteData(0x00);
  	tft_WriteData(0x18);

  	tft_WriteCommand(ILI9341_DFUNCTR);    // Display Function Control
  	tft_WriteData(0x08);
  	tft_WriteData(0x82);
  	tft_WriteData(0x27);

  	tft_WriteCommand(0xF2);    // 3Gamma Function Disable
  	tft_WriteData(0x00);

  	tft_WriteCommand(ILI9341_GAMMASET);    //Gamma curve selected
  	tft_WriteData(0x01);

  	tft_WriteCommand(ILI9341_GMCTRP1);    //Set Gamma
  	tft_WriteData(0x0F);
  	tft_WriteData(0x31);
  	tft_WriteData(0x2B);
  	tft_WriteData(0x0C);
  	tft_WriteData(0x0E);
  	tft_WriteData(0x08);
  	tft_WriteData(0x4E);
  	tft_WriteData(0xF1);
  	tft_WriteData(0x37);
  	tft_WriteData(0x07);
  	tft_WriteData(0x10);
  	tft_WriteData(0x03);
  	tft_WriteData(0x0E);
  	tft_WriteData(0x09);
  	tft_WriteData(0x00);

  	tft_WriteCommand(ILI9341_GMCTRN1);    //Set Gamma
  	tft_WriteData(0x00);
  	tft_WriteData(0x0E);
  	tft_WriteData(0x14);
  	tft_WriteData(0x03);
  	tft_WriteData(0x11);
  	tft_WriteData(0x07);
  	tft_WriteData(0x31);
  	tft_WriteData(0xC1);
  	tft_WriteData(0x48);
  	tft_WriteData(0x08);
  	tft_WriteData(0x0F);
  	tft_WriteData(0x0C);
  	tft_WriteData(0x31);
  	tft_WriteData(0x36);
  	tft_WriteData(0x0F);

  	tft_WriteCommand(ILI9341_SLPOUT);    //Exit Sleep
  	delay_ms(120);
  	tft_WriteCommand(ILI9341_DISPON);    //Display on
}

#if (ILI9341_USE_RESET == pdON)
void tft_Reset(void) {
    ili9341_ResetOff();
    delay_ms(5);
	ili9341_ResetOn();
    delay_ms(20);
	ili9341_ResetOff();
    delay_ms(150);
}
#endif

void tft_WriteCommand(u8 c) {
  	ili9341_Command();
  	ili9341_Enable();
  	ili9341_TransferByte(c);
  	ili9341_Disable();
}

void tft_WriteData(u8 c) {
	ili9341_Data();
  	ili9341_Enable();
  	ili9341_TransferByte(c);
  	ili9341_Disable();
}

u8 tft_ReadData(void) {
   	ili9341_Data();
   	ili9341_Enable();
   u8 r = ili9341_TransferByte(0x00);
   ili9341_Disable();

   return r;
}

u8 tft_ReadCommand(u8 c) {
   ili9341_Command(); // command
   ili9341_Enable();
   ili9341_TransferByte(0xD9);  // woo sekret command?
   ili9341_Data(); // data
   ili9341_TransferByte(0x10);
   ili9341_Disable();

   ili9341_Command();
   ili9341_Enable();
   ili9341_TransferByte(c);

   ili9341_Data();
  	u8 r = ili9341_TransferByte(0x00);
   ili9341_Disable();

   return r;
}

//##################################################################################################################
//
//##################################################################################################################
void tft_SetAddrWindow(u16 x0, u16 y0, u16 x1, u16 y1) {

  tft_WriteCommand(ILI9341_CASET); // Column addr set
  tft_WriteData(x0 >> 8);
  tft_WriteData(x0 & 0xFF);     // XSTART
  tft_WriteData(x1 >> 8);
  tft_WriteData(x1 & 0xFF);     // XEND

  tft_WriteCommand(ILI9341_PASET); // Row addr set
  tft_WriteData(y0>>8);
  tft_WriteData(y0);     // YSTART
  tft_WriteData(y1>>8);
  tft_WriteData(y1);     // YEND

  tft_WriteCommand(ILI9341_RAMWR); // write to RAM
}

void tft_PushColor(u16 color) {
  	ili9341_Data();
  	ili9341_Enable();
  	ili9341_TransferByte(color >> 8);
  	ili9341_TransferByte(color);
  	ili9341_Disable();
}

void tft_DrawPixel(s16 x, s16 y, u16 color) {
	if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return;

  	tft_SetAddrWindow(x,y,x+1,y+1);

  	ili9341_Data();
  	ili9341_Enable();
  	ili9341_TransferByte(color >> 8);
  	ili9341_TransferByte(color);
	ili9341_Disable();
}

void tft_DrawFastVLine(s16 x, s16 y, s16 h, u16 color) {
  	// Rudimentary clipping
  	if((x >= _width) || (y >= _height)) return;

  	if((y+h-1) >= _height) h = _height-y;
  	tft_SetAddrWindow(x, y, x, y+h-1);

  	u8 hi = color >> 8, lo = color;

 	ili9341_Data();
  	ili9341_Enable();
  	while (h--) {
    	ili9341_TransferByte(hi);
    	ili9341_TransferByte(lo);
  	}
  	ili9341_Disable();
}

void tft_DrawFastHLine(s16 x, s16 y, s16 w, u16 color) {
  	if((x >= _width) || (y >= _height)) return;
  	if((x+w-1) >= _width)  w = _width-x;
  	tft_SetAddrWindow(x, y, x+w-1, y);

  	u8 hi = color >> 8, lo = color;
  	ili9341_Data();
  	ili9341_Enable();
  	while (w--) {
    	ili9341_TransferByte(hi);
    	ili9341_TransferByte(lo);
  	}
  	ili9341_Disable();
}

void tft_FillScreen(u16 color) {
  	tft_FillRect(0, 0,  _width, _height, color);
}

// fill a rectangle
void tft_FillRect(s16 x, s16 y, s16 w, s16 h, u16 color) {
  	// rudimentary clipping (drawChar w/big text requires this)
  	if((x >= _width) || (y >= _height)) return;
  	if((x + w - 1) >= _width)  w = _width  - x;
  	if((y + h - 1) >= _height) h = _height - y;

  	tft_SetAddrWindow(x, y, x+w-1, y+h-1);

  	u8 hi = color >> 8, lo = color;

  	ili9341_Data();
  	ili9341_Enable();
  	for(y=h; y>0; y--) {
    	for(x=w; x>0; x--) {
      		ili9341_TransferByte(hi);
      		ili9341_TransferByte(lo);
    	}
  	}
  	ili9341_Disable();
}


// Pass 8-bit (each) R,G,B, get back 16-bit packed color
u16 tft_Color565(u8 r, u8 g, u8 b) {
  	return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}


#define MADCTL_MY  0x80
#define MADCTL_MX  0x40
#define MADCTL_MV  0x20
#define MADCTL_ML  0x10
#define MADCTL_RGB 0x00
#define MADCTL_BGR 0x08
#define MADCTL_MH  0x04

void tft_SetRotation(u8 m) {
  	tft_WriteCommand(ILI9341_MADCTL);
  	switch (m % 4) { // can't be higher than 3
   	case 1:
    	tft_WriteData(MADCTL_MV | MADCTL_BGR);
     	_width  = gfxHEIGHT;
     	_height = gfxWIDTH;
     	break;
  	case 2:
    	tft_WriteData(MADCTL_MY | MADCTL_BGR);
     	_width  = gfxWIDTH;
     	_height = gfxHEIGHT;
    	break;
   	case 3:
    	tft_WriteData(MADCTL_MX | MADCTL_MY | MADCTL_MV | MADCTL_BGR);
     	_width  = gfxHEIGHT;
     	_height = gfxWIDTH;
     	break;
     default: // case 0:
     	tft_WriteData(MADCTL_MX | MADCTL_BGR);
     	_width  = gfxWIDTH;
     	_height = gfxHEIGHT;
     	break;
  	}
}

void tft_InvertDisplay(uint i) {
  	tft_WriteCommand(i ? ILI9341_INVON : ILI9341_INVOFF);
}

u16 tft_Width(void) {
	return _width;
}

u16 tft_Height(void) {
	return _height;
}



//// Rather than a bazillion ili9341_WriteCommand() and ili9341_WriteData() calls, screen
//// initialization commands and arguments are organized in these tables
//// stored in PROGMEM.  The table may look bulky, but that's mostly the
//// formatting -- storage-wise this is hundreds of bytes more compact
//// than the equivalent code.  Companion function follows.
//#define DELAY 0x80

//// Companion code to the above tables.  Reads and issues
//// a series of LCD commands stored in PROGMEM byte array.
//void Adafruit_ILI9341::commandList(u8 *addr) {
//
//  u8  numCommands, numArgs;
//  u16 ms;
//
//  numCommands = pgm_read_byte(addr++);   // Number of commands to follow
//  while(numCommands--) {                 // For each command...
//    ili9341_WriteCommand(pgm_read_byte(addr++)); //   Read, issue command
//    numArgs  = pgm_read_byte(addr++);    //   Number of args to follow
//    ms       = numArgs & DELAY;          //   If hibit set, delay follows args
//    numArgs &= ~DELAY;                   //   Mask out delay bit
//    while(numArgs--) {                   //   For each argument...
//      ili9341_WriteData(pgm_read_byte(addr++));  //     Read, issue argument
//    }
//
//    if(ms) {
//      ms = pgm_read_byte(addr++); // Read post-command delay time (ms)
//      if(ms == 255) ms = 500;     // If 255, delay for 500 ms
//      delay(ms);
//    }
//  }
//}
//
//
